﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:32
    /// 描 述：关联类型表
    /// </summary>
    public class ec_Wire_Group_TemplateService
    {
        #region 仓储
        Repository<ec_Wire_Group_TemplateEntity> _wireGroupTemplateRepository => new Repository<ec_Wire_Group_TemplateEntity>();
        Repository<ec_Wire_GroupEntity> _wireGroupRepository => new Repository<ec_Wire_GroupEntity>();
        //Repository<ec_SofttagEntity> _softtagRepository => new Repository<ec_SofttagEntity>();
        #endregion
        #region 获取数据
        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_Wire_Group_TemplateEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                var tableName = ProjectSugar.TableName<ec_Wire_Group_TemplateEntity>(ProjectId);
                return _wireGroupTemplateRepository.AsQueryable().AS(tableName).First(x => x.WireGroupTemplateID == keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                var tableName = ProjectSugar.TableName<ec_Wire_Group_TemplateEntity>(ProjectId);
                _wireGroupTemplateRepository.AsDeleteable().AS(tableName).Where(x => x.WireGroupTemplateID == keyValue).ExecuteCommand();
                tableName = ProjectSugar.TableName<ec_Wire_GroupEntity>(ProjectId);
                _wireGroupRepository.AsDeleteable().AS(tableName).Where(x => x.WireGroupTemplateID == keyValue).ExecuteCommand();
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_Wire_Group_TemplateEntity entity, string ProjectId)
        {
            try
            {
                string tableName = ProjectSugar.TableName<ec_Wire_Group_TemplateEntity>(ProjectId);
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    _wireGroupTemplateRepository.AsUpdateable(entity).AS(tableName).ExecuteCommand();
                }
                else
                {
                    entity.Create();
                    _wireGroupTemplateRepository.AsInsertable(entity).AS(tableName).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 初始化项目信号模板（从 公司级 复制到 项目级）
        /// </summary> 
        /// <param name="WireGroupTemplateID">公司级下的某个模板</param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        public void InitProjectWireGroupFromTemplate(string WireGroupTemplateID, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                //清空数据
                //var softtagTableName = ProjectSugar.TableName<ec_SofttagEntity>(ProjectId);
                var wireGroupTableName = ProjectSugar.TableName<ec_Wire_GroupEntity>(ProjectId);
                var wireGroupTemplateTableName = ProjectSugar.TableName<ec_Wire_Group_TemplateEntity>(ProjectId);
                //_softtagRepository.AsDeleteable().AS(softtagTableName).ExecuteCommand();

                if (_wireGroupRepository.AsQueryable().AS(wireGroupTableName).Count() > 0)
                {
                    return;//项目里已经有了，就不会了     
                    //_wireGroupRepository.AsDeleteable().AS(wireGroupTableName).ExecuteCommand(); //
                }
                try
                {
                    _wireGroupTemplateRepository.AsDeleteable().AS(wireGroupTemplateTableName).ExecuteCommand();//本来这个模板在项目级里就没有意义
                }
                catch (Exception)
                {

                    throw;
                }


                //拷贝数据
                var wireGroupTemplate = _wireGroupTemplateRepository.GetFirst(x => x.WireGroupTemplateID == WireGroupTemplateID);
                if (wireGroupTemplate == null)
                {
                    return;//无效的模板id
                }
                var wireGroups = _wireGroupRepository.AsQueryable().Where(x => x.WireGroupTemplateID == WireGroupTemplateID).ToList();
                _wireGroupRepository.AsInsertable(wireGroups).AS(wireGroupTableName).ExecuteCommand();

                //数据字典
                var groups = wireGroups.GroupBy(x => x.Signal_Group).Select(x => x.Key).ToList();//应该有的分组
                var dataitemTableName = ProjectSugar.TableName<ec_dataitemEntity>(ProjectId);
                var dataitemDetailTableName = ProjectSugar.TableName<ec_dataitemdetailEntity>(ProjectId);

                var item = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(dataitemTableName).First(x => x.DataItemCode == "Be_Signal_Group");
                if (item == null)
                {
                    item = new ec_dataitemEntity();
                    item.Create();
                    item.UpDataItemID = "0";
                    item.DataItemName = "信号分组";
                    item.DataItemCode = "Be_Signal_Group";
                    item.OrderID = 5;
                    item.IsEnabled = 1;
                    SqlSugarHelper.Db.Insertable(item).AS(dataitemTableName).ExecuteCommand();
                }
                var list = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(dataitemDetailTableName)
                    .Where(x => x.DataItemID == item.DataItemID && groups.Contains(x.DataItemCode)).ToList();//项目级里的信号分组
                var details = new List<ec_dataitemdetailEntity>();
                var max = list.Max(x => x.OrderID);
                groups.ForEach(x =>
                {
                    if (!list.Any(y => y.DataItemID == item.DataItemID && y.DataItemCode == x))
                    {
                        var detail = new ec_dataitemdetailEntity();
                        detail.Create();
                        detail.DataItemID = item.DataItemID;
                        detail.UpDataItemDetailID = "0";
                        detail.DataItemName = "excel导入时新增，请编辑其正确含义";
                        detail.DataItemCode = x;
                        detail.OrderID = ++max;
                        detail.IsEnabled = 1;
                        details.Add(detail);
                    }
                });
                SqlSugarHelper.Db.Insertable(details).AS(dataitemDetailTableName).ExecuteCommand();

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

    }
}
